package com.youlu.campus.service.sms;

import com.youlu.campus.entity.*;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserSubTemplateMsgService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    /**
     * 获取用户订阅消息状态
     *
     * @param currentUser
     * @return
     */
    public Map<String, Boolean> getSumStatus(UserPO currentUser) {
        Map<String, Boolean> result = new HashMap<>(1);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUser.getId()));
        List<UserSubTemplateMsg> list = this.mongoTemplate.find(query, UserSubTemplateMsg.class);
        if (CollectionUtils.isEmpty(list)) {
            result.put("sumMsg", Boolean.TRUE);
            return result;
        }
        //只要订阅中有一个接收消息，就是打开
        long count =
                list.stream().filter(userSubTemplateMsg -> UserSubTemplateMsg.OPEN_RECEIVE_MSG.equals(userSubTemplateMsg.getStatus())).count();
        if (count > 0) {
            result.put("sumMsg", Boolean.TRUE);
            return result;
        }
        result.put("sumMsg", Boolean.FALSE);
        return result;
    }

    /**
     * 用户操作订阅消息
     *
     * @param currentUser
     * @param subMsgType  1、取消订阅消息 2、打开订阅消息
     */
    public void subMsg(UserPO currentUser, Integer subMsgType) {
        log.info("【订阅消息】用户操作订阅消息 userId - >{},sumMsg ->{}", currentUser.getId(), subMsgType);
        Date now = new Date();
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUser.getId()));
        boolean exists = this.mongoTemplate.exists(query, UserSubTemplateMsg.class);
        if (exists) {
            Update update = new Update();
            if (subMsgType == 2) {
                update.set("status", UserSubTemplateMsg.OPEN_RECEIVE_MSG);
            } else {
                update.set("status", UserSubTemplateMsg.CLOSE_RECEIVE_MSG);
            }
            update.set("updatedTime", now);
            this.mongoTemplate.updateMulti(query, update, UserSubTemplateMsg.class);
            return;
        }
        UserInfoExtend userInfoExtend = userInfoExtendService.findByUserIdAndAppId(currentUser);
         query = new Query();
        query.addCriteria(Criteria.where("accountInfoId").is(currentUser.getId()));
        List<WechatH5UserPO> h5UserList = this.mongoTemplate.find(query, WechatH5UserPO.class);
        if (CollectionUtils.isNotEmpty(h5UserList)) {
            List<UserSubTemplateMsg> h5SubUserList = h5UserList.stream().map(wechatH5UserPO -> {
                UserSubTemplateMsg userSubTemplateMsg = new UserSubTemplateMsg();
                userSubTemplateMsg.setAppId(wechatH5UserPO.getAppId());
                userSubTemplateMsg.setUserId(wechatH5UserPO.getAccountInfoId());
                userSubTemplateMsg.setOpenId(wechatH5UserPO.getOpenId());
                userSubTemplateMsg.setUnionId(wechatH5UserPO.getUnionId());
                userSubTemplateMsg.setAvatarUrl(wechatH5UserPO.getAvatarUrl());
                userSubTemplateMsg.setNickName(currentUser.getNickName());
                userSubTemplateMsg.setAppId(wechatH5UserPO.getAppId());
                if (subMsgType == 2) {
                    userSubTemplateMsg.setStatus(UserSubTemplateMsg.OPEN_RECEIVE_MSG);
                }else{
                    userSubTemplateMsg.setStatus(UserSubTemplateMsg.CLOSE_RECEIVE_MSG);
                }
                if (Objects.nonNull(userInfoExtend)) {
                    userSubTemplateMsg.setMobile(userInfoExtend.getMobile());
                    userSubTemplateMsg.setEmail(userInfoExtend.getEmail());
                }
                userSubTemplateMsg.setCreatedTime(now);
                userSubTemplateMsg.setUpdatedTime(now);
                return userSubTemplateMsg;
            }).collect(Collectors.toList());
            this.mongoTemplate.insertAll(h5SubUserList);
        }
        List<WechatMiniUserPO> wechatMiniUserList = this.mongoTemplate.find(query, WechatMiniUserPO.class);
        if (CollectionUtils.isEmpty(wechatMiniUserList)) {
            return;
        }
        List<UserSubTemplateMsg> miniSubUserList = wechatMiniUserList.stream().map(wechatH5UserPO -> {
            UserSubTemplateMsg userSubTemplateMsg = new UserSubTemplateMsg();
            userSubTemplateMsg.setAppId(wechatH5UserPO.getAppId());
            userSubTemplateMsg.setUserId(wechatH5UserPO.getAccountInfoId());
            userSubTemplateMsg.setUnionId(wechatH5UserPO.getUnionId());
            userSubTemplateMsg.setOpenId(wechatH5UserPO.getOpenId());
            userSubTemplateMsg.setAvatarUrl(wechatH5UserPO.getAvatarUrl());
            userSubTemplateMsg.setNickName(currentUser.getNickName());
            userSubTemplateMsg.setAppId(wechatH5UserPO.getAppId());
            if (Objects.nonNull(userInfoExtend)) {
                userSubTemplateMsg.setMobile(userInfoExtend.getMobile());
                userSubTemplateMsg.setEmail(userInfoExtend.getEmail());
            }
            if (subMsgType == 2) {
                userSubTemplateMsg.setStatus(UserSubTemplateMsg.OPEN_RECEIVE_MSG);
            }else{
                userSubTemplateMsg.setStatus(UserSubTemplateMsg.CLOSE_RECEIVE_MSG);
            }
            userSubTemplateMsg.setUpdatedTime(now);
            userSubTemplateMsg.setCreatedTime(now);
            return userSubTemplateMsg;
        }).collect(Collectors.toList());
        this.mongoTemplate.insertAll(miniSubUserList);
    }
}
